package cn.glinks.liuhe.utils;

import android.app.ActivityManager;
import android.content.Context;

import java.util.List;

import cn.glinks.liuhe.app.AppApplication;

/**
 * Android APP基本工具
 * 
 * @author chengyh(chengyh@chitek.com)
 * 
 */
public class AppCommonUtils {
	private final static String TAG = "AppCommonUtils";
	
	
	/********************************************************
     * 
	 * 判断程序前后台切换处理
	 * 
	 ********************************************************/
	/**
     * 判断程序是否是从后台切换到前台(在onStart中调用, 仅在一个位置调用)
     *
     * @return
     */
	public static boolean checkBackgroundToForeground(Context context) {
		if (isAppOnForeground()) {
			LogUtils.logd("切换到->前台");
			if (((AppApplication) context.getApplicationContext()).getAppLastStatus() == 1) {
				LogUtils.logd("后台->切换到->前台");
				((AppApplication) context.getApplicationContext()).setAppLastStatus(0);
				return true;
			}
		} else {
			LogUtils.logd("切换到->后台");
		}
		return false;
	}

	/**
     * 判断程序是否是从前台切换到后台(在onStop中调用)
     *
     * @return
     */
	public static boolean checkForegroundToBackground(Context context) {
		if (isAppOnForeground()) {
			LogUtils.logd("切换到->前台");
		} else {
			LogUtils.logd("切换到->后台");
			if (((AppApplication) context.getApplicationContext()).getAppLastStatus() == 0) {
				LogUtils.logd("前台->切换到->后台");
				((AppApplication) context.getApplicationContext()).setAppLastStatus(1);
				return true;
			}
		}
		return false;
	}
    
    /**
     * 判断程序是否在前台运行
     *
     * @return
     */
	public static boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) AppApplication.getAppContext().getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = AppApplication.getAppContext().getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }
}
